#! /usr/bin/env python
## This file is part of biopy.
## Copyright (C) 2013 Joseph Heled
## Author: Joseph Heled <jheled@gmail.com>
## See the files gpl.txt and lgpl.txt for copying conditions.

from __future__ import division

import argparse, sys, os.path

parser = argparse.ArgumentParser(description = """Root unrooted trees.""")

parser.add_argument("-m", "--midpoint", action="store_true", default = False,
                    help="""Use midpoint rooting""")

parser.add_argument("-o", "--nexus", metavar="FILE",
                    help="Name of trees file.", default = None)

parser.add_argument('trees', metavar='FILE-OR-TREE', help="Trees file (or explicit tree)")

from biopy import INexus, __version__
from biopy.treeutils import toNewick, TreeLogger, \
     rootAtMidpoint, rootByTipVarianceOptimization

options = parser.parse_args()

targ = options.trees
if os.path.isfile(targ) :
  trees = list(INexus.INexus().read(file(targ)))
else :
  if targ[0] != '(' :
    print >> sys.stderr, "Command line argument is not a file or a newick tree"
    sys.exit(1)
    
  try :
    trees = [INexus.Tree(targ)]
  except Exception,e:
    print >> sys.stderr, "*** Error: failed to parse tree: ",e.message,"[",targ,"]"
    sys.exit(1)

tlog = None
if options.nexus :
  tlog = TreeLogger(options.nexus, argv = sys.argv, version = __version__)

for count,tree in enumerate(trees) :
  if options.midpoint :
    rtree = rootAtMidpoint(tree)
  else :
    rtree = rootByTipVarianceOptimization(tree)
    
  if tlog :
    tlog.outTree(rtree, name = tree.name)
  else :
    print rtree
    
if tlog:
  tlog.close()
